<template>
  <scroll
    class="suggest"
    ref="suggest"
    :data="result"
    :pullup="pullup"
    :beforeScroll="beforeScroll"
    @scrollToEnd="searchMore"
    @beforeScroll="listScroll"
  >
    <ul class="suggest-list" ref="suggestList">
      <li
        class="suggest-item"
        v-for="(item, index) in result"
        :key="index"
        @click="selectItem(item)"
      >
        <div class="icon">
          <i :class="getIconCls(item)"></i>
        </div>

        <div class="name">
          <p class="text" v-html="getDisplayName(item)"></p>
        </div>
      </li>

      <loading v-show="hasMore" title=""></loading>
    </ul>

    <div class="no-result-wrapper" v-show="!hasMore && !result.length">
      <no-result title="抱歉，暂无搜索结果"></no-result>
    </div>
  </scroll>
</template>


<script type="text/ecmascript-6">
import Scroll from 'common/scroll/scroll'
import { search } from 'api/search'
import { ERR_OK } from 'api/config'
import Loading from 'common/loading/loading'
import NoResult from 'common/no-result/no-result'
import { createSong, isValidMusic, processSongsUrl } from 'assets/js/song'
import Singer from 'assets/js/singer'
import { mapMutations, mapActions } from 'vuex'


const TYPE_SINGER = 'singer'
const perpage = 20

export default {
  name: 'suggest',
  props: {
    showSinger: {
      type: Boolean,
      default: true
    },
    query: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      page: 1,
      hasMore: true,
      pullup: true,
      beforeScroll: true,
      result: []
    }
  },
  methods: {
    ...mapMutations({
      setSinger: 'SET_SINGER'
    }),
    ...mapActions([
      'insertSong'
    ]),
    search() {
      this.page = 1
      this.$refs.suggest.scrollTo(0, 0)
      this.hasMore = true
      search(this.query, this.page, this.showSinger, perpage).then(res => {
        if (res.code === ERR_OK) {
          this._genResult(res.data).then(result => {
            this.result = result
            setTimeout(() => {
              this._checkMore(res.data)
            }, 20)
          })
        }
      })
    },
    searchMore() {
      if (!this.hasMore) {
        return
      }
      this.page++
      search(this.query, this.page, this.showSinger, perpage).then(res => {
        if (res.code === ERR_OK) {
          this._genResult(res.data).then(result => {
            this.result = this.result.concat(result)
            setTimeout(() => {
              this._checkMore(res.data)
            }, 20)
          })
        }
      })
    },
    listScroll() {
      this.$emit('listScroll')
    },
    _genResult(data) {
      let ret = []
      if (data.zhida && data.zhida.singerid && this.page === 1) {
        ret.push({ ...data.zhida, ...{ type: TYPE_SINGER } })
      }

      return processSongsUrl(this._normalizeSongs(data.song.list)).then(songs => {
        ret = ret.concat(songs)
        return ret
      })
    },
    _normalizeSongs(list) {
      let ret = []
      list.forEach(musicData => {
        if (isValidMusic(musicData)) {
          ret.push(createSong(musicData))
        }
      })
      return ret
    },
    _checkMore(data) {
      const song = data.song
      if (!song.list.length || (song.curnum + (song.curpage - 1) * perpage) >= song.totalnum) {
        this.hasMore = false
      } else {

      }
      if (this.$refs.suggest.$el.clientHeight > this.$refs.suggestList.clientHeight) {
        this.searchMore()
      }
    },

    selectItem(item) {
      if (item.type === TYPE_SINGER) {
        const singer = new Singer({
          id: item.singermid,
          name: item.singername
        })

        this.$router.push({
          path: `./search/${singer.id}`
        })

        this.setSinger(singer)
      } else {
        this.insertSong(item)
      }

      this.$emit('select', item)
    },


    getIconCls(item) {
      if (item.type === TYPE_SINGER) {
        return 'icon-mine'
      } else {
        return 'icon-music'
      }
    },
    getDisplayName(item) {
      if (item.type === TYPE_SINGER) {
        return item.singername
      } else {
        return `${item.name}-${item.singer}`
      }
    },
  },
  watch: {
    query(newQuery) {
      if (!newQuery) {
        return
      }
      this.result = []
      this.search(newQuery)
      // console.log(this.result);
    }
  },
  components: {
    Scroll,
    Loading,
    NoResult
  }
}
</script>

<style lang="stylus" scoped ref="stylesheet/stylus">
@import '~assets/stylus/variable';
@import '~assets/stylus/mixin';

.suggest {
  height: 100%;
  overflow: hidden;

  .suggest-list {
    padding: 0 30px;

    .suggest-item {
      display: flex;
      align-items: center;
      padding-bottom: 20px;

      .icon {
        flex: 0 0 30px;
        width: 30px;

        [class^='icon-'] {
          font-size: 14px;
          color: $color-text-d;
        }
      }

      .name {
        flex: 1;
        font-size: $font-size-medium;
        color: $color-text-d;
        overflow: hidden;

        .text {
          no-wrap();
        }
      }
    }
  }

  .no-result-wrapper {
    position: absolute;
    width: 100%;
    top: 50%;
    transform: translateY(-50%);
  }
}
</style>